#ifndef WEBSOCKET_H
#define WEBSOCKET_H

#include <QWebSocket>
#include <QString>
#include <QThread>
#include <QTimer>

#include "json_utils.h"
#include "project_global.h"

class PROJECT_EXPORT WebsocketObject : public QObject
{
    Q_OBJECT
public:
    WebsocketObject(QObject *parent = 0);
    ~WebsocketObject();

signals:
    void sigConnectState(bool connect_state);         // 连接成功后，connect_state为true，反之为false
    void sigTextReceived(QString msg);                // 接收到ROS数据

public slots:
    void sltConnect(QString ip, QString port);  // 连接
    void sltDisConnect();                       // 断开连接

    void sltRosSubOrUnsub(QString option, QString topic);
    void sltRosPublish(QString topic, QJsonObject msg);
    void sltRosService(QString service,  QJsonObject request);

private slots:
    void sltRetry();
    void sltConnectSuccess();              // socket建立成功后，触发该函数
    void onTextReceived(QString msg);      // 收到Sev端的数据时，触发该函数
    void sltDisConnected();                // socket连接断开后，触发该函数

private:
    QWebSocket* web_socket;                // websocket类
    QTimer* connect_timer;

    int connect_times = 0;                 // 用于解决连接未成功时，及时停止连接，并提醒用户检查网络
    QUrl url;
};

class PROJECT_EXPORT WebsocketThread : public QObject
{
    Q_OBJECT
public:
    WebsocketThread(QObject* parent = 0);
    ~WebsocketThread();

public:
    void startWorking();
    void stopWorking();

    void Connect(QString ip, QString port);                  // 连接
    void disConnect();                                       // 断开连接

    void rosSubScriber(QString topic);                       // 订阅话题
    void rosUnSubScriber(QString topic);                     // 取消订阅
    void rosPublisher(QString topic, QJsonObject msg);       // 发布话题
    void rosServicer(QString service,  QJsonObject request); // 调用服务

signals:

    // 私有信号
    void sigWebSocketConnect(QString ip, QString port);
    void sigWebSocketDisconnect();

    void sigRosSubOrUnSub(QString option, QString topic);
    void sigRosPublish(QString topic, QJsonObject msg);
    void sigRosService(QString service,  QJsonObject request);

    // 对外信号
    void sigConnectState(bool connect_state);                // 连接成功后，connect_state为true，反之为false
    void sigTextReceived(QString msg);

private slots:
    void sltConnectState(bool connect_state);
    void sltTextReceived(QString msg);

private:
    QThread m_thread;
    WebsocketObject* websocket_object;
};

#endif // WEBSOCKET_H
